package com.zang.oss.qiniu;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

/**
 * @author Zhang Qiang
 * @date 2019/10/17 14:00
 */
public class QiniuUpload {


    private final String QINIU_ACCESSKEY = "JR4Ii1eYcFdi7qhmRMW3qc2JtEVxFbHDl5MGPVIm";
    private final String QINIU_SECRETKEY = "r8fj2Jf29gIRr-usCZt-Uw6yZTUzXKRWRkQPg2aS";
    private final String QINIU_BACKET = "caqun-hd";


    public void uploadTest(){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //如果是Windows情况下，格式是 D:\\qiniu\\test.png
        String localFilePath = "D:\\cache\\1k.jpg";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = "1k.jpg";
        Auth auth = Auth.create(QINIU_ACCESSKEY, QINIU_SECRETKEY);
        String upToken = auth.uploadToken(QINIU_BACKET);
        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }


}
